<?php
/**
 * Created by PhpStorm.
 * User: liya
 * Date: 2024/11/18
 * Time: 15:43
 */

namespace App\Model;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DefenderDraw extends BaseModel
{
    protected $table = 'defender_draw';
    protected $awardLogTable = 'defender_draw_award_log';
    protected $manualAward = 'Defender_draw_manual_award';

    protected $poolTable = 'Defender_draw_award_pool';
    protected $giftTable = 'gift_library';

    public function getUserStatistic(Request $request){
        $limit = $request->input('limit', 10);
        $page = $request->input('page',1);
        $luck_id = $request->input('luckId',0);
        $gender = $request->input('gender',0);
        $uuid = $request->input('uuid',0);
        $startDate = $request->input('startDate',date('Y-m-d'));
        $endDate = $request->input('endDate',date('Y-m-d'));
        $startDate = date('Y-m-d 00:00:00',strtotime($startDate));
        $endDate = date('Y-m-d 23:59:59',strtotime($endDate));
        $sql = DB::connection($this->connection)->table($this->awardLogTable)
            ->leftJoin('user','user.user_id','=',$this->awardLogTable.'.user_id')
            ->leftJoin($this->table,$this->table.'.id','=',$this->awardLogTable.'.luck_id')
            ->whereBetween($this->awardLogTable.'.created_at',[$startDate,$endDate]);
        if($luck_id){
            $sql->where('luck_id',$luck_id);
        }
        if($gender){
            $sql->where('gender',$gender);
        }
        if($uuid){
            $sql->where('uuid',$uuid);
        }
        $res = $sql->groupBy($this->awardLogTable.'.user_id','luck_id')
            ->selectRaw('zb_'.$this->awardLogTable.'.user_id,luck_id,sum(zb_'.$this->awardLogTable.'.price * num) as award_price,sum(num) * zb_'.$this->table.'.price as luck_price,(sum(zb_'.$this->awardLogTable.'.price * num) - sum(num) * zb_'.$this->table.'.price) as profit ,uuid,nickname,zb_'.$this->table.'.name as luck_name')
            ->orderBy('profit' ,'asc')
            ->paginate($limit, ['*'], 'page', $page);
        $luckData = DB::connection($this->connection)->table($this->table)
            ->select('id','price','name')->get();
        $luckData =  $this->objToArray($luckData);
        $luckPrice = array_column($luckData,'price','id');
        $luckName = array_column($luckData,'name','id');
        foreach ($res as $key => $value){
            $res[$key]->award_price = intval($value->award_price);
//            $res[$key]->luck_price = intval($luckPrice[$value->luck_id] * $value->luck_num);
//            $res[$key]->profit = intval(intval($value->award_price) - $res[$key]->luck_price);
            $res[$key]->profit = intval($value->profit);
            $res[$key]->output_ratio = $res[$key]->luck_price != 0 ?number_format($value->award_price / $res[$key]->luck_price * 100,4):'0.0000';
//            $res[$key]->luck_name = $luckName[$value->luck_id];
//            unset($res[$key]->luck_num);
            unset($res[$key]->luck_id);
        }
        $res = $this->objToArray($res);
        $allSql = DB::connection($this->connection)->table($this->awardLogTable)
            ->leftJoin('user','user.user_id','=',$this->awardLogTable.'.user_id')
            ->whereBetween('created_at',[$startDate,$endDate]);
        if($luck_id){
            $allSql->where('luck_id',$luck_id);
        }
        if($gender){
            $allSql->where('gender',$gender);
        }
        $allRes = $allSql->groupBy('luck_id')
            ->selectRaw('sum(price * num) as award_price,sum(num) as luck_num,count(DISTINCT zb_'.$this->awardLogTable.'.user_id) as user_num,luck_id')
            ->get();
        $allRes = $this->objToArray($allRes);
        $res['all'] = [];
        foreach ($allRes as $allvalue) {
            $allData['all_award_price'] = intval($allvalue['award_price']);
            $allData['all_luck_price'] = intval($allvalue['luck_num'] * $luckPrice[$allvalue['luck_id']]);
            $allData['all_user_num'] = intval($allvalue['user_num']);
            $allData['output_ratio'] = $allData['all_luck_price'] != 0 ?number_format($allData['all_award_price'] / $allData['all_luck_price'] * 100,4):'0.0000';;
            $allData['luck_id'] = $allvalue['luck_id'];
            $allData['luck_name'] = $luckName[$allvalue['luck_id']];
            $res['all'][] = $allData;
        }
        return $res;
    }
    public function getType(){
        $res = DB::connection($this->connection)->table($this->table)
            ->select('id','name')
            ->where('deleted', 0)
            ->get();

        return $this->objToArray($res);
    }

    public function getdefenderDraw($where = [], $page=1, $limit=10){
        $res = DB::connection($this->connection)
            ->table($this->table)
            ->select('id','name', 'en_name', 'price', 'tag', 'status', 'deleted', 'start', 'end')
            ->where('deleted', 0)
            //->offset($limit * ($page - 1))
            //->limit($limit)
            ->paginate($limit, ['*'], 'page', $page);
        // ->get();

        return $this->objToArray($res);
    }

    public function editdefenderDraw($params){
        $res = curl_request(getKkaudioApiUrl() . '/inner/luckDraw/edit', $params, 'json', 'POST');
        write_log('editLuckDraw','setData',[$params, getKkaudioApiUrl() . '/inner/luckDraw/edit', $res]);

        return $res;
    }

    public function getManualAward (Request $request){
        $limit = $request->input('limit', 10);
        $page = $request->input('page',1);
        $luck_id = $request->input('luckId',0);
        $uuid = $request->input('uuid',0);

        $sql = DB::connection($this->connection)->table($this->manualAward)
            ->leftJoin('user','user.user_id','=',$this->manualAward.'.user_id');
        if($luck_id){
            $sql->where('luck_id',$luck_id);
        }
        if($uuid){
            $sql->where('uuid',$uuid);
        }
        $res = $sql->where('deleted',0)
            ->selectRaw('zb_'.$this->manualAward.'.user_id,luck_id,status,type,award_id,uuid,nickname,timeout,id')
            ->orderBy('created_at' ,'desc')
            ->paginate($limit, ['*'], 'page', $page);
        $res = $this->objToArray($res);
        $luckData = DB::connection($this->connection)->table($this->table)
            ->select('id','name')->get();
        $luckData =  $this->objToArray($luckData);
        $luckName = array_column($luckData,'name','id');
        $awardIds = array_column($res['data'],'award_id');
        $awardData = DB::connection($this->connection)->table('gift_library')
            ->whereIn('gift_id',$awardIds)
            ->select('gift_id','name')
            ->get();
        $awardData = $this->objToArray($awardData);
        $awardData = $awardData?array_column($awardData,'name','gift_id'):[];
        foreach ($res['data'] as $key => $value){
            $res['data'][$key]['luck_name'] = $luckName[$value['luck_id']];
            $res['data'][$key]['award_nume'] = $awardData[$value['award_id']]??'';
            if ($value['status'] == 0 && strtotime($value['timeout']) < time()){
                $res['data'][$key]['status'] = 2 ;
            }
        }

        return $res;

    }

    public function addManualAward($awardData){
        $data = [
            'luck_id'   => $awardData['luckId'],
            'user_id'   => $awardData['user_id'],
            'award_id'  => $awardData['awardId'],
            'type'      => $awardData['type']??1
        ];
        return curl_request(getKkaudioApiUrl() . '/inner/defenderDraw/addManualAward', $data, 'json', 'POST');
    }

    public function delManualAward($id){
        $data = [
            'id'   => $id,
        ];
        return curl_request(getKkaudioApiUrl() . '/inner/defenderDraw/delManualAward', $data, 'json', 'POST');
    }


    public function getActivityPool(Request $request){
        $limit = $request->input('limit', 10);
        $page = $request->input('page',1);
        $pool_id = $request->input('pool_id',0);
        $desc = $request->input('desc','');

        $sql = DB::connection($this->connection)->table($this->poolTable);
        if ($pool_id) $sql->where('id',$pool_id);
        if ($desc) $sql->where('desc',$desc);

        $data = $sql->where('deleted',0)
            ->orderBy('luck_id','asc')
            ->orderBy('id','desc')
            ->paginate($limit, ['*'], 'page', $page);
        $data = $this->objToArray($data);
        $giftIds = [];
        foreach ($data['data'] as $key => $pool){
            $awardDatas = json_decode($pool['pool'],true);
            if (!$awardDatas){
                continue;
            }
            foreach ($awardDatas as $awardData){
                if ($awardData['type'] == 1){
                    $giftIds[] = $awardData['id'];
                }
            }
        }
        $giftList = DB::connection($this->connection)->table($this->giftTable)
            ->whereIn('gift_id',$giftIds)
            ->get(['gift_id','name']);
        $giftList = $this->objToArray($giftList);
        $giftList = array_column($giftList,'name','gift_id');
        foreach ($data['data'] as $key => $pool){
            unset($data['data'][$key]['deleted']);
            $awardDatas = json_decode($pool['pool'],true);
            $data['data'][$key]['pool'] = $awardDatas;
            if (!$awardDatas){
                continue;
            }
            foreach ($awardDatas as $awardKey => $awardData) {
                if ($awardData['type'] == 1){
                    $data['data'][$key]['pool'][$awardKey]['name'] = isset($awardData['id']) && $awardData['type'] == 1 && isset($giftList[$awardData['id']]) ?$giftList[$awardData['id']]:'';
                }
            }
        }



        return $data;

    }

    public function addActivityPool($desc){
        $data = [
            'desc'   => $desc,
        ];
        return curl_request(getKkaudioApiUrl() . '/inner/defenderDraw/addActivityPool', $data, 'json', 'POST');

    }

    public function delActivityPool($id){
        $data = [
            'id'   => $id,
        ];
        return curl_request(getKkaudioApiUrl() . '/inner/defenderDraw/delActivityPool', $data, 'json', 'POST');

    }

    public function setActivityPool($pools){
        write_log('ActivityPool','setData',[$pools, getKkaudioApiUrl() . '/inner/defenderDraw/setActivityPool']);
        return curl_request(getKkaudioApiUrl() . '/inner/defenderDraw/setActivityPool', ['pools'=>$pools], 'json', 'POST');
    }

    public function upActivityPool($id,$desc){
        $data = [
            'id'   => $id,
            'desc'   => $desc,
        ];
        return curl_request(getKkaudioApiUrl() . '/inner/defenderDraw/upActivityPool', $data, 'json', 'POST');

    }

    //擂主游戏抽奖统计
    public function awardStatisticsList(Request $request)
    {
        $luck_id = $request->input('luck_id');
        $created_st = $request->input('created_st');
        $created_ed = $request->input('created_ed');

        $query = DB::connection($this->connection)->table($this->awardLogTable);
        if(!empty($created_st)) {
            $created_st = date("Y-m-d H:i:s", strtotime($created_st));
            $query = $query->where('created_at', '>=', $created_st);
        }
        if(!empty($created_ed)) {
            $created_ed = date("Y-m-d H:i:s", strtotime($created_ed));
            $query = $query->where('created_at', '<=', $created_ed);
        }
        if(!empty($luck_id)) {
            $query = $query->where('luck_id', $luck_id);
        }

        $result = $query->selectRaw("luck_id, award_id as gift_id, sum(num) as giftNum, sum(num*price) as totalPirce")
            ->groupBy('luck_id', 'award_id')
            ->get();
        $result = objToArray($result);
        if(!empty($result)) {
            $giftIds = array_column($result, 'gift_id');
            $giftList = DB::connection($this->connection)->table($this->giftTable)->whereIn('gift_id', $giftIds)->get();
            $giftList = array_column(objToArray($giftList), null, 'gift_id');

            $lickList = DB::connection($this->connection)->table($this->table)->select('id', 'name')->get();
            $lickList = array_column(objToArray($lickList), null, 'id');

            foreach($result as &$val) {
                $val['luckName'] = empty($lickList[$val['luck_id']]['name']) ? '' : $lickList[$val['luck_id']]['name'];
                $val['giftName'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
            }
        }

        return $result;
    }




}
